#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct empleyee
{
	char name[20];	//姓名
	int salary;		//工资
}emp[100];


void save(char *filename,int n)
{
		FILE *fp;
		int i;
		if((fp=fopen(filename,"ab+"))==NULL) //追加方式打开二进制文件
		{
			perror("fopen error!\n");
			exit(0);
		}
		for(i=0;i<n;i++)
		{
			//将一组数据写入到fp所指文件中
			//成功写入返回值为1(即count)
			if(fwrite(&emp[i],sizeof(struct empleyee),1,fp)!=1)
			{
				printf("file write error\n");
			}	
		}
		fclose(fp);
}
void show(char *filename,int n)
{
	int i;
	FILE *fp;
	if((fp=fopen(filename,"rb"))==NULL)
	{
		perror("fopen error!\n");
		exit(0);
	}
	for(i=0;fread(&emp[i],sizeof(struct empleyee),1,fp)!=0;i++)
	{
		//从fp所指文件中读取数据到数组s中
		printf("%s%15d\n",emp[i].name,emp[i].salary);
	}
	fclose(fp);
	printf("\n");
}

void DeleteFileRecord(char *filename,int number)
{
	int i;
	printf("please input name and salary:\n");
	for(i=0;i<number;i++)
	{
		printf("NO%d:\n",i+1);
		scanf("%s%d",emp[i].name,&emp[i].salary);
	}
	save(filename,number);//调用函数save将输入数组的数据保存到文件
	printf("original date:\n");
	show(filename,number);
	printf("please input the name which you want to delete:\n");
	char empname[20];
	int flag,j;
	scanf("%s",empname);
	for(flag=1,i=0;flag&&i<number+1;i++)
	{
		if(strcmp(empname,emp[i].name)==0)
		{
			for(j=i;j<number-1+1;j++)
			{
				//查找到要删除信息的位置后将后面信息前移
				strcpy(emp[j].name,emp[j+1].name);
				emp[j].salary=emp[j+1].salary;
			}
			flag=0;
		}
	}
	if(!flag)
		number-=1;
	else
		printf("Not Fond!\n");
	printf("Now,the content of file:\n");
	FILE *fp;
	fp=fopen(filename,"wb");//只写打开文件
	for(i=0;i<number;i++)
	{
		fwrite(&emp[i],sizeof(struct empleyee),1,fp);
	}
	fclose(fp);
	show(filename,number-1);
}


int main()
{
	char filename[50];
	int number;
	printf("please input the filename:\n");
	scanf("%s",filename);
	printf("please input the number of empleyee:\n");
	scanf("%d",&number);
	DeleteFileRecord(filename,number);
	
	return 0;
}


